package com.example.stock.ui.order;

import android.annotation.SuppressLint;
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.example.stock.base.BaseViewModel;
import com.example.stock.base.Result;
import com.example.stock.config.Config;
import com.example.stock.http.ApiException;
import com.example.stock.http.ICallback;
import com.example.stock.http.ResponseCallback;
import com.example.stock.model.GoodsData;
import com.example.stock.model.GoodsOrderBean;
import com.example.stock.util.DBUtil;
import com.example.stock.util.SharedPreferencesUtils;
import com.example.stock.util.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class GoodsViewModel extends BaseViewModel {

    public MutableLiveData<Result<List<GoodsOrderBean>>> goods = new MutableLiveData<>();
    public MutableLiveData<Result<GoodsOrderBean>> uploadResult = new MutableLiveData<>();

    public GoodsViewModel(@NonNull Application application) {
        super(application);
    }

    /**
     * 获取到货单同步接口
     */
    @SuppressLint("CheckResult")
    public void getGoodOrders() {
        getShowDialog().setValue(true);
        Observable.just(1).map(new Function<Integer, List<GoodsOrderBean>>() {
            @NonNull
            @Override
            public List<GoodsOrderBean> apply(@NonNull Integer integer) throws Exception {
                return DBUtil.getInstance().queryGoodsOrderAll();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<GoodsOrderBean>>() {
                    @Override
                    public void accept(List<GoodsOrderBean> beans) throws Exception {
                        getShowDialog().setValue(false);
                        Result<List<GoodsOrderBean>> result = new Result<>();
                        if (beans != null && beans.size() > 0) {
                            result.setCode("0001");
                        } else {
                            result.setCode("0002");
                            result.setMsg("数据为空，请更新货单");
                        }
                        result.setData(beans);
                        goods.setValue(result);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        getShowDialog().setValue(false);
                        Result<List<GoodsOrderBean>> result = new Result<>();
                        result.setCode("0003");
                        result.setMsg("e : " + throwable.getMessage());
                        goods.setValue(result);
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void upload(GoodsOrderBean chooseItem) {
        getShowDialog().setValue(true);
        Observable.just(1).map(new Function<Integer, List<GoodsOrderBean>>() {
            @NonNull
            @Override
            public List<GoodsOrderBean> apply(@NonNull Integer integer) throws Exception {
                List<GoodsOrderBean> items = new ArrayList<>();
                List<GoodsData> data = DBUtil.getInstance().queryGoodsDataByDjh(chooseItem, 0, Integer.MAX_VALUE);
                chooseItem.setDataList(data);
                items.add(chooseItem);
                return items;
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<GoodsOrderBean>>() {
            @Override
            public void accept(@NonNull List<GoodsOrderBean> beans) throws Exception {
                String toJson = new Gson().toJson(beans.get(0), GoodsOrderBean.class);
                api.savePogeneral12("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ibus=\"http://intf.base.ws.nc/IBusiPDABillService\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <ibus:savePogeneral>\n" +
                        "         <!--Optional:-->\n" +
                        "         <string> " + toJson +"</string>\n" +
                        "      </ibus:savePogeneral>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>").enqueue(new ResponseCallback<String>(GoodsViewModel.this) {
                    @Override
                    public void onSuccess(String o) {
                        Result<GoodsOrderBean> result = new Result<>();
                        if(!TextUtils.isEmpty(o) && o.contains("soap:Envelope")){
                            String res = Utils.analysisFault(o, "return");
                            assert res != null;
                            String s = res.replaceAll("&lt;", "<").replaceAll("&gt;",">");
                            String resData = Utils.analysisFault(s, "code");
                            String resMsgData = Utils.analysisFault(s, "msg");
                            result.setCode(resData);
                            result.setMsg(resMsgData);
                        }
                        result.setData(chooseItem);
                        uploadResult.setValue(result);
                    }

                    @Override
                    public void onFailure(ApiException e) {
                        super.onFailure(e);
                        Result<GoodsOrderBean> result = new Result<>();
                        result.setCode("0003");
                        result.setMsg("上传失败" + e.getMessage());
                        uploadResult.setValue(result);
                    }
                });
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                getShowDialog().setValue(false);
                Utils.getInstance().showToast("本地数据查询失败，请重试");
            }
        });
    }
}